﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using ZHDJ.AppInterface.Common;
using ZHDJ.AppInterface.Models;
using ZHDJ.Core;
using ZHDJ.Data.BLL;

namespace ZHDJ.AppInterface.Controllers
{
    public class UserController : ApiController
    {
        #region 登录
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        //[Authorize]
        [HttpPost]
        public ReturnResult Login([FromBody]PartyBuildingUser user)
        {
            var result = new ReturnResult();
            bool isFlag = true;
            string loginID = string.Empty;
            var userinfo = new PartyBuildingUser();
            string logMsg = "";
            var currentDay = (DateTime.Now.Month * 100 + DateTime.Now.Day).ToString().PadLeft(4, '0');

            if (string.IsNullOrEmpty(user.UserName) || string.IsNullOrEmpty(user.UserPwd))
            {
                result.code = "201";
                result.msg = "用户名，密码不能为空";
            }


            try
            {
                if (isFlag)
                {
                    DataSet dsMember;
                    dsMember = InterfaceHelper.GetMembersByFilter(" Userno='" + user.UserName + "' and  runSate<>'4' ");
                    if (dsMember == null || dsMember.Tables[0].Rows.Count == 0)
                    {
                        result.code = "201";
                        result.msg = "用户名不存在";

                        isFlag = false;
                    }
                    else if (dsMember.Tables[0].Rows.Count > 1)
                    {
                        result.code = "201";
                        result.msg = "用户名不唯一，请联系管理员解决";

                        isFlag = false;
                    }
                    else
                    {
                        loginID = dsMember.Tables[0].Rows[0]["LoginID"].ToString();
                    }
                }

                if (isFlag)
                {
                    //param.pwd = CommonUtils.GetMD5(param.pwd);
                    isFlag = InterfaceHelper.PasswordIsCorrect(loginID, user.UserPwd);

                    if (!isFlag)
                    {
                        result.code = "201";
                        result.msg = "密码输入不正确";
                    }
                }

                if (isFlag)
                {
                    DataSet ds = InterfaceHelper.GetMembersLoginInfo(loginID);
                    if (ds != null && ds.Tables[0].Rows.Count > 0)
                    {
                        userinfo.UserId = ds.Tables[0].Rows[0]["user_id"].ToString();
                        userinfo.UserName = ds.Tables[0].Rows[0]["user_name"].ToString();
                        userinfo.UserTrueName = ds.Tables[0].Rows[0]["user_truename"].ToString();
                        userinfo.UserPwd = "";
                        userinfo.UserBranchId = ds.Tables[0].Rows[0]["branch_id"].ToString();
                        userinfo.UserScore = ds.Tables[0].Rows[0]["is_can_test"].ToString();
                        userinfo.IsPartyWorkers = false;

                        ////统计APP登录人数
                        //InterfaceHelper.StatisticAPPLogin(ds.Tables[0].Rows[0]["user_id"].ToString(), userinfo.UserBranchId);
                        ////登陆积分
                        //PartyScoreHelper.Add(() => PartyScoreHelper.AddDayLogin(ds.Tables[0].Rows[0]["user_id"].ToString()));

                        result.code = "200";
                        result.msg = "";
                    }
                }
            }
            catch (Exception ex)
            {
                result.code = "400";
                result.msg = "操作异常，多次出现请联系管理员";
                logMsg = ex.Message + ":" + ex.StackTrace;
            }

            string urlPara = Request.RequestUri.AbsoluteUri;

            CommonUtils.InsertMobileInterfaceLog("UserLogin", SerializeHelper.JsonSerializer<PartyBuildingUser>(user), urlPara + ";" + logMsg + currentDay);
            result.result = userinfo;
            return result;
        }
        #endregion

        #region 内部测试登录
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        //[Authorize]
        [HttpPost]
        public ReturnResult LoginTest([FromBody]PartyBuildingUser user)
        {
            var result = new ReturnResult();
            bool isFlag = true;
            string loginID = string.Empty;
            var userinfo = new PartyBuildingUser();
            string logMsg = "";

            try
            {
                if (isFlag)
                {
                    DataSet dsMember;
                    dsMember = InterfaceHelper.GetMembersByFilter(" Userno='" + user.UserName + "' and  runSate<>'4' ");
                    if (dsMember == null || dsMember.Tables[0].Rows.Count == 0)
                    {
                        result.code = "201";
                        result.msg = "用户名不存在";

                        isFlag = false;
                    }
                    else if (dsMember.Tables[0].Rows.Count > 1)
                    {
                        result.code = "201";
                        result.msg = "用户名不唯一，请联系管理员解决";

                        isFlag = false;
                    }
                    else
                    {
                        loginID = dsMember.Tables[0].Rows[0]["LoginID"].ToString();
                    }
                }

                if (isFlag)
                {
                    DataSet ds = InterfaceHelper.GetMembersLoginInfo(loginID);
                    if (ds != null && ds.Tables[0].Rows.Count > 0)
                    {
                        userinfo.UserId = ds.Tables[0].Rows[0]["user_id"].ToString();
                        userinfo.UserName = ds.Tables[0].Rows[0]["user_name"].ToString();
                        userinfo.UserTrueName = ds.Tables[0].Rows[0]["user_truename"].ToString();
                        userinfo.UserPwd = "";
                        userinfo.UserBranchId = ds.Tables[0].Rows[0]["branch_id"].ToString();
                        userinfo.UserScore = ds.Tables[0].Rows[0]["is_can_test"].ToString();
                        userinfo.IsPartyWorkers = false;

                        ////统计APP登录人数
                        //InterfaceHelper.StatisticAPPLogin(ds.Tables[0].Rows[0]["LoginID"].ToString(), userinfo.UserBranchId);
                        ////登陆积分
                        //PartyScoreHelper.Add(() => PartyScoreHelper.AddDayLogin(ds.Tables[0].Rows[0]["LoginID"].ToString()));

                        result.code = "200";
                        result.msg = "";
                    }
                }
            }
            catch (Exception ex)
            {
                result.code = "400";
                result.msg = "操作异常，多次出现请联系管理员";
                logMsg = ex.Message + ":" + ex.StackTrace;
            }
            result.result = userinfo;
            return result;
        }
        #endregion

        #region 退出
        [HttpPost]
        public ReturnResult Logout()
        {

            return new ReturnResult()
            {
                code = "200",
                result = "成功",
                msg = ""
            };

        }
        #endregion

        #region 获取个人信息
        /// <summary>
        /// 获取个人信息
        /// </summary>
        /// <param name="LoginID">登录ID</param>
        /// <returns></returns>
        [HttpPost]
        public ReturnResult GetPartyBuildingUserModel([FromBody]PartyOrgMember model)
        {
            var result = new ReturnResult();

            //获取Session
            if (string.IsNullOrWhiteSpace(model.UserId))
            {
                result.code = "201";
                result.result = "";
                result.msg = "请您先登录！";
            }
            else
            {
                PartyOrgMember newModel = InterfaceHelper.GetPartyBuildingUserModel(model.UserId);

                result.code = "200";
                result.result = newModel;
                result.msg = "success";
            }
            return result;
        }
        #endregion

        #region 上传Logo
        [HttpPost]
        public ReturnResult UpFile(dynamic obj)
        {
            ReturnResult model = new ReturnResult();
            string image = Convert.ToString(obj.imgurl);//Base64字符编码图片
            string Extension = Convert.ToString(obj.Extension);//扩展名
            string Description = Convert.ToString(obj.Description);//描述
            int Size = Convert.ToInt32(obj.Size);//文件大小
            string CreateBy = Convert.ToString(obj.CreateBy);//创建人
            try
            {
                int i = InterfaceHelper.UpLogo(image, Extension, Description, Size, CreateBy);

                if (i > 0)
                {
                    model.code = "200";
                    model.msg = "上传成功！";
                }
                else
                {
                    model.code = "201";
                    model.msg = "上传失败！";
                }
            }
            catch (Exception ex)
            {
                model.code = "201";
                model.msg = ex.Message;
            }

            return model;
        }

        [HttpPost]
        public ReturnResult NewUpFile(dynamic obj)
        {
            ReturnResult model = new ReturnResult();
            string image = Convert.ToString(obj.imgurl);//Base64字符编码图片
            string Extension = Convert.ToString(obj.Extension);//扩展名
            string Description = Convert.ToString(obj.Description);//描述
            int Size = Convert.ToInt32(obj.Size);//文件大小
            string CreateBy = Convert.ToString(obj.CreateBy);//创建人
            try
            {
                InterfaceHelper.NewUpLogo(image, Extension, Description, Size, CreateBy);
                ImageModel imageModel = InterfaceHelper.UpImge(image, Extension);
                if (imageModel != null)
                {
                    model.code = "200";
                    model.result = imageModel;
                    model.msg = "上传成功！";
                }
                else
                {
                    model.code = "201";
                    model.msg = "上传失败！";
                }
            }
            catch (Exception ex)
            {
                model.code = "201";
                model.msg = ex.Message;
            }

            return model;
        }
        #endregion

        #region 获取我的积分信息
        [HttpPost]
        public ReturnResult GetMyPoints(dynamic obj)
        {
            MyPoints model = new MyPoints();
            string LoginID = Convert.ToString(obj.LoginID);
            string branchID = Convert.ToString(obj.BranchID);
            model.BranchName = InterfaceHelper.GetBranchNameBId(branchID);
            model.Points = InterfaceHelper.SumMemberintegral("Member", LoginID);
            model.Rank = InterfaceHelper.GetRankingByObjectID("Member", LoginID);
            model.BranchRank = InterfaceHelper.GetRankingByObjectID("Member", LoginID, branchID);
            return new ReturnResult()
            {
                code = "200",
                result = model,
                msg = "success"
            };
        }
        #endregion

        #region 获取我的党费缴纳记录
        [HttpPost]
        public ReturnResult GetMyMemberCost(dynamic obj)
        {
            IList<PartyMemberCost> list = new List<PartyMemberCost>();
            int pageIndex = Convert.ToInt32(obj.pageIndex);
            int pageSize = Convert.ToInt32(obj.pageSize);
            string LoginID = Convert.ToString(obj.LoginID);
            DataTable dt = InterfaceHelper.GetMyMemberCost(pageIndex, pageSize, LoginID);
            if (dt.Rows.Count > 0)
                list = DataTableToListModel<PartyMemberCost>.ConvertToModel(dt);

            return new ReturnResult()
            {
                code = "200",
                result = list,
                msg = "success"
            };
        }
        #endregion

        #region 修改姓名
        [HttpPost]
        public ReturnResult UpdateUserNameByLoginID(dynamic obj)
        {
            ReturnResult result = new ReturnResult();
            string LoginID = Convert.ToString(obj.LoginID);
            string UserName = Convert.ToString(obj.UserName);
            string res = InterfaceHelper.UpdateUserNameByLoginID(LoginID, UserName);
            if (!string.IsNullOrWhiteSpace(res))
            {
                result.code = "200";
                result.result = res;
                result.msg = "success";
            }
            else
            {
                result.code = "201";
                result.result = res;
                result.msg = "error";
            }
            return result;
        }
        #endregion

        #region 修改性别
        [HttpPost]
        public ReturnResult UpdateGenderByLoginID(dynamic obj)
        {
            ReturnResult result = new ReturnResult();
            string LoginID = Convert.ToString(obj.LoginID);
            string Gender = Convert.ToString(obj.Gender);
            string res = InterfaceHelper.UpdateGenderByLoginID(LoginID, Gender);
            if (!string.IsNullOrWhiteSpace(res))
            {
                result.code = "200";
                result.result = res;
                result.msg = "success";
            }
            else
            {
                result.code = "201";
                result.result = res;
                result.msg = "error";
            }
            return result;
        }
        #endregion

        #region 修改生日
        [HttpPost]
        public ReturnResult UpdateBirthdayByLoginID(dynamic obj)
        {
            ReturnResult result = new ReturnResult();
            string LoginID = Convert.ToString(obj.LoginID);
            string Birthday = Convert.ToString(obj.Birthday);
            string res = InterfaceHelper.UpdateBirthdayByLoginID(LoginID, Birthday);
            if (!string.IsNullOrWhiteSpace(res))
            {
                result.code = "200";
                result.result = res;
                result.msg = "success";
            }
            else
            {
                result.code = "201";
                result.result = res;
                result.msg = "error";
            }
            return result;
        }
        #endregion

        #region 获取生成验证码
        [HttpPost]
        public ReturnResult GetValiCode(dynamic obj)
        {
            string UserName = Convert.ToString(obj.UserName);
            string code = InterfaceHelper.GetValiCode(UserName);
            return new ReturnResult
            {
                code = "200",
                result = code,
                msg = "success"
            };
        }
        #endregion

        #region 根据用户名或者姓名获取用户数据
        [HttpPost]
        public ReturnResult GetMemberByUserNoOrUserName(dynamic obj)
        {
            string keyword = Convert.ToString(obj.keyword);
            IList<PartyOrgMember> list = new List<PartyOrgMember>();
            DataTable dt = InterfaceHelper.GetMemberByUserNoOrUserName(keyword);
            if (dt.Rows.Count > 0)
                list = DataTableToListModel<PartyOrgMember>.ConvertToModel(dt);

            return new ReturnResult()
            {
                code = "200",
                result = list,
                msg = "success"
            };
        }
        #endregion

        #region 登出操作更改登录状态
        [HttpPost]
        public ReturnResult UpdateLoginState(dynamic obj)
        {
            ReturnResult result = new ReturnResult();
            PartyVisitStatisticLoginApp model = new PartyVisitStatisticLoginApp();
            model.UserID = Convert.ToString(obj.UserId);
            model.IsLogin = false;

            if (InterfaceHelper.UpdatePartyVisitStatisticLoginAppByUserID(model) > 0)
            {
                result.code = "200";
                result.msg = "success";
            }
            else
            {
                result.code = "201";
                result.msg = "error";
            }
            return result;
        }
        #endregion
    }
}
